package fudan.secret.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.*;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.apache.struts2.json.annotations.JSON;

import fudan.secret.util.HibernateSessionFactory;
import fudan.secret.domain.User;

public class RegisterAction extends ActionSupport{
  private String uname;
  private String unickname;
  private String upassword;
  private String uemail;
  private Map<String,String> map;
  private static int nid = 2;
 
  @JSON(serialize=false)
  public String getUname(){
	  return uname;
  }
  
  public void setUname(String name){
	  uname = name;
  }
  
  @JSON(serialize=false)
  public String getUnickname(){
	  return unickname;
  }
  
  public void setUnickname(String nickname){
	  unickname = nickname;
  }
  
  @JSON(serialize=false)
  public String getUpassword(){
	  return upassword;
  }
  
  public void setUpassword(String password){
	  upassword = password;
  }
  
  @JSON(serialize=false)
  public String getUemail(){
	  return uemail;
  }
  
  public void setUemail(String email){
	  uemail = email;
  }
  
  public Map<String, String> getResult() {  
      return map;  
   }  
  
  
  public String execute() throws Exception{
	  User user = new User();
	  Session session = HibernateSessionFactory.getSession();
	  Transaction tx = null;
	  map = new HashMap<String,String>();
	  if(uname.length()<6 || uname==null || unickname.length()<6 || unickname==null ||
			  upassword.length()<6 || upassword==null || uemail==null){
		  map.put("register", "false");
		  session.close();
		  return SUCCESS;
	  }
	  try{
		  String hql ="from User where uname= :name or unickname= :nickname";
		  Query query = session.createQuery(hql);
		  query.setParameter("name", uname);
		  query.setParameter("nickname", unickname);
		  List<User> users = query.list();
		  if(users != null && users.size() > 0){
			map.put("register", "false");
		  } else {
	        user.setUname(uname);
	        user.setUnickname(unickname);
		    user.setUpassword(upassword);
		    user.setUemail(uemail);
		    tx = session.beginTransaction();
		    session.saveOrUpdate(user);
		    tx.commit();
		    map.put("register", "true");
		  }
	  } catch(Exception e) {
		  e.printStackTrace();
		  tx.rollback();
		  map.put("register", "error");
	  } finally {
		  session.close();
	  }
	  return SUCCESS;
  }
}